package com.example.commonutils.handler;

import com.example.commonutils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class, Controller.class}) //只要类上面加了这两个注解，都会被处理
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
//    Cause: java.sql.SQLIntegrityConstraintViolationException:
//    Duplicate entry '狮子头' for key 'order_dish_dish_name_uindex'
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error().message(msg);
        }
        return R.error().message("未知错误");
    }
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R exceptionHandler(HttpMessageNotReadableException ex){
        if (ex.getMessage().contains("not a valid representation")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[11] + "格式不正确，请输入数字";
            return R.error().message(msg);
        }
        if (ex.getMessage().contains("not a valid Integer value")){
            return R.error().message("请输入整数");
        }
        return R.error().message("未知错误");
    }
    @ExceptionHandler(NoqueueException.class)
    public R exceptionHandler(NoqueueException e){
        e.printStackTrace();
        return R.error().message(e.getMsg());
    }
}
